package com.lichongbing.openai.controller;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

@RestController
@RequestMapping("/proxy")
public class ReverseProxyController {

    private final WebClient webClient;

    public ReverseProxyController(WebClient.Builder webClientBuilder) {
        this.webClient = webClientBuilder.baseUrl("https://api.openai.com").build();
    }

    @RequestMapping("/**")
    public Mono<ResponseEntity<String>> proxyRequest(
            @RequestHeader HttpHeaders headers,
            @RequestBody(required = false) String body,
            @RequestParam MultiValueMap<String, String> queryParams,
            HttpServletRequest servletRequest) {

        String path = servletRequest.getRequestURI().replaceFirst("/proxy", "");
        WebClient.RequestBodySpec uriSpec = webClient
                .method(HttpMethod.valueOf(servletRequest.getMethod()))  // 获取请求方法
                .uri(uriBuilder -> uriBuilder.path(path).queryParams(queryParams).build())
                .headers(httpHeaders -> httpHeaders.addAll(headers));

        if (body != null && !body.isEmpty()) {
            uriSpec.contentType(MediaType.APPLICATION_JSON).bodyValue(body);
        }

        return uriSpec.retrieve()
                .toEntity(String.class);
    }
}
